package com.crt.nexus.security.component;

import com.crt.nexus.security.annotation.Inner;
import lombok.Getter;
import lombok.NonNull;
import lombok.Setter;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.regex.Pattern;

/**
 * 资源服务器对外直接暴露URL
 */
@ConfigurationProperties(prefix = "security.oauth2.ignore")
public class PermitUrlProperties implements InitializingBean, ApplicationContextAware {

    private static final Pattern PATTERN = Pattern.compile("\\{(.*?)}");

    private ApplicationContext applicationContext;

    @Getter
    @Setter
    private List<String> urls = new ArrayList<>();

    @Override
    public void afterPropertiesSet() {
        RequestMappingHandlerMapping mapping = applicationContext.getBean(RequestMappingHandlerMapping.class);
        Map<RequestMappingInfo, HandlerMethod> map = mapping.getHandlerMethods();
        map.keySet().forEach(info -> {
            HandlerMethod handlerMethod = map.get(info);
            Inner method = AnnotationUtils.findAnnotation(handlerMethod.getMethod(), Inner.class);
            // 获取方法上边的注解, 替代 path variable 为 *
            Optional.ofNullable(method).ifPresent(inner -> {
                if (info.getPatternsCondition() != null) {
                    info.getPatternsCondition().getPatterns().forEach(url -> urls.add(PATTERN.matcher(url).replaceAll("*")));
                }
            });
            // 获取类上边的注解, 替代 path variable 为 *
            Inner controller = AnnotationUtils.findAnnotation(handlerMethod.getBeanType(), Inner.class);
            Optional.ofNullable(controller).ifPresent(inner -> {
                if (info.getPatternsCondition() != null) {
                    info.getPatternsCondition().getPatterns().forEach(url -> urls.add(PATTERN.matcher(url).replaceAll("*")));
                }
            });
        });
    }

    @Override
    public void setApplicationContext(@NonNull ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

}
